//
//  LXTabBar.m
//  SevenFM
//
//  Created by seven on 2018/4/11.
//  Copyright © 2018年 seven. All rights reserved.
//

#import "LXTabBar.h"
#import "LXMiddleView.h"
#import "UIView+LXLayout.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface LXTabBar()

@property (nonatomic, weak) LXMiddleView *middleView;

@end

@implementation LXTabBar

/**
 懒加载中间控件

 @return 中间的按钮控件
 */
- (LXMiddleView *)middleView {
    if (_middleView == nil) {
        LXMiddleView *middleView = [LXMiddleView shareInstance];
        [self addSubview:middleView];
        _middleView = middleView;
    }
    return _middleView;
}
///初始化设置
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupInit];
    }
    return self;
}

- (void)setupInit {
    //设置样式，去除tabbar上面的黑线
    self.barStyle = UIBarStyleBlack;
    //设置tabbar背景图片
    NSBundle *currentBundle = [NSBundle bundleForClass:[self class]];
    NSString *imagePath = [currentBundle pathForResource:@"tabbar_bg@3x.png" ofType:nil inDirectory:@"SevenFMMain.bundle"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    self.backgroundImage = image;

    //添加一个按钮，准备放中间
    CGFloat width = 65;
    CGFloat height = 65;
    self.middleView.frame = CGRectMake((kScreenWidth - width) * 0.5, (kScreenHeight - height), width, height);
}

- (void)setMiddleClickBlock:(void (^)(BOOL))middleClickBlock {
    self.middleView.middleClcikBlock = middleClickBlock;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSInteger count = self.items.count;
    //1.遍历所有子控件
    NSArray *subViews = self.subviews;
    //2.确定单个控件大小
    CGFloat btnW = self.width / (count + 1);
    CGFloat btnH = self.height;
    CGFloat btnY = 5;

    NSInteger index = 0;
    for (UIView *subView in subViews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (index == count / 2) {
                index ++;
            }
            CGFloat btnX = index * btnW;
            subView.frame = CGRectMake(btnX, btnY, btnW, btnH);
            index ++;
        }
    }
    self.middleView.width = 65;
    self.middleView.height = 65;
    self.middleView.centerX = self.frame.size.width * 0.5;
    self.middleView.y = self.height - self.middleView.height;
//    self.middleView.y = -15;
//    NSLog(@"%@", NSStringFromCGRect(self.middleView.frame));
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    //设置允许交互的区域
    //1.转换点击在tabbar上的坐标点，到中间按钮
    CGPoint pointInMiddleBtn = [self convertPoint:point toView:self.middleView];
    //2.确定中间按钮的圆心
    CGPoint middleBtnCenter = CGPointMake(33, 33);
    //3.计算点击的位置距离圆心的位置
    CGFloat distance = sqrt(pow(pointInMiddleBtn.x - middleBtnCenter.x, 2) + pow(pointInMiddleBtn.y - middleBtnCenter.y, 2));
    //4.判定中间按钮区域之外
    if (distance > 33 && pointInMiddleBtn.y < 18) {
        return NO;
    }
    return YES;
}
@end
